// 建筑管理 Store

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Building, BuildingTemplate, BuildingUpgrade, PlanetaryBonus } from '@/types'
import { useResourcesStore } from './resources'

export const useBuildingsStore = defineStore('buildings', () => {
  const resourcesStore = useResourcesStore()

  // 状态
  const buildings = ref<Record<string, Building>>({})
  const buildingTemplates = ref<Record<string, BuildingTemplate>>({})
  const buildQueue = ref<BuildingQueueItem[]>([])
  const planetaryBonuses = ref<PlanetaryBonus[]>([])

  interface BuildingQueueItem {
    id: string
    buildingId: string
    planetId: string
    startTime: number
    endTime: number
    progress: number
  }

  // 计算属性
  const buildingsByCategory = computed(() => {
    const categorized: Record<string, Building[]> = {
      infrastructure: [],
      industrial: [],
      research: [],
      military: [],
      special: []
    }

    Object.values(buildings.value).forEach(building => {
      if (!categorized[building.category]) {
        categorized[building.category] = []
      }
      categorized[building.category].push(building)
    })

    return categorized
  })

  const buildingsByPlanet = computed(() => {
    const byPlanet: Record<string, Building[]> = {}

    Object.values(buildings.value).forEach(building => {
      if (building.planetId) {
        if (!byPlanet[building.planetId]) {
          byPlanet[building.planetId] = []
        }
        byPlanet[building.planetId].push(building)
      }
    })

    return byPlanet
  })

  const totalBuildingEffects = computed(() => {
    const effects: Record<string, number> = {}

    Object.values(buildings.value).forEach(building => {
      if (building.isActive) {
        building.effects.forEach(effect => {
          const key = `${effect.type}_${effect.target}`
          effects[key] = (effects[key] || 0) + effect.value
        })
      }
    })

    return effects
  })

  const buildingCount = computed(() => {
    return Object.keys(buildings.value).length
  })

  const activeBuildingCount = computed(() => {
    return Object.values(buildings.value).filter(b => b.isActive).length
  })

  // 动作
  function initializeBuildingTemplates() {
    // 基础设施建筑模板
    buildingTemplates.value['residential_complex'] = {
      id: 'residential_complex',
      name: '居住区',
      description: '为人口提供居住空间',
      category: 'infrastructure',
      baseStats: {
        production: [],
        consumption: [{ resourceId: 'energy', amount: 2 }],
        capacity: { population: 1000 },
        efficiency: 1.0,
        powerConsumption: 2,
        workerCapacity: 0
      },
      upgrades: [],
      unlockConditions: [],
      icon: 'icon-residential',
      maxLevel: 10
    }

    buildingTemplates.value['power_plant'] = {
      id: 'power_plant',
      name: '发电厂',
      description: '生产能量',
      category: 'infrastructure',
      baseStats: {
        production: [{ resourceId: 'energy', amount: 10, efficiency: 1.0, isActive: true }],
        consumption: [{ resourceId: 'gas', amount: 2 }],
        capacity: {},
        efficiency: 1.0,
        powerConsumption: 0,
        workerCapacity: 50
      },
      upgrades: [],
      unlockConditions: [],
      icon: 'icon-power-plant',
      maxLevel: 5
    }

    // 工业建筑模板
    buildingTemplates.value['metal_mine'] = {
      id: 'metal_mine',
      name: '金属矿场',
      description: '开采金属资源',
      category: 'industrial',
      baseStats: {
        production: [{ resourceId: 'metal', amount: 5, efficiency: 1.0, isActive: true }],
        consumption: [{ resourceId: 'energy', amount: 3 }],
        capacity: {},
        efficiency: 1.0,
        powerConsumption: 3,
        workerCapacity: 100
      },
      upgrades: [],
      unlockConditions: [],
      icon: 'icon-metal-mine',
      maxLevel: 8
    }

    buildingTemplates.value['factory'] = {
      id: 'factory',
      name: '工厂',
      description: '生产工业产品',
      category: 'industrial',
      baseStats: {
        production: [{ resourceId: 'alloy', amount: 2, efficiency: 1.0, isActive: true }],
        consumption: [
          { resourceId: 'metal', amount: 4 },
          { resourceId: 'energy', amount: 5 }
        ],
        capacity: {},
        efficiency: 1.0,
        powerConsumption: 5,
        workerCapacity: 200
      },
      upgrades: [],
      unlockConditions: [],
      icon: 'icon-factory',
      maxLevel: 6
    }

    // 研究建筑模板
    buildingTemplates.value['research_center'] = {
      id: 'research_center',
      name: '研究中心',
      description: '进行科技研究',
      category: 'research',
      baseStats: {
        production: [],
        consumption: [{ resourceId: 'energy', amount: 8 }],
        capacity: { research: 100 },
        efficiency: 1.0,
        powerConsumption: 8,
        workerCapacity: 300
      },
      upgrades: [],
      unlockConditions: [],
      icon: 'icon-research',
      maxLevel: 5
    }

    // 军事建筑模板
    buildingTemplates.value['shipyard'] = {
      id: 'shipyard',
      name: '造船厂',
      description: '建造舰船',
      category: 'military',
      baseStats: {
        production: [],
        consumption: [{ resourceId: 'energy', amount: 15 }],
        capacity: { shipbuilding: 1 },
        efficiency: 1.0,
        powerConsumption: 15,
        workerCapacity: 500
      },
      upgrades: [],
      unlockConditions: [],
      icon: 'icon-shipyard',
      maxLevel: 3
    }
  }

  function buildBuilding(templateId: string, planetId: string): boolean {
    const template = buildingTemplates.value[templateId]
    if (!template) return false

    // 检查解锁条件
    if (!checkUnlockConditions(template.unlockConditions)) return false

    // 检查建造成本
    const costs = calculateBuildCosts(template, 1)
    if (!resourcesStore.canAfford(costs)) return false

    // 扣除资源
    if (!resourcesStore.payCosts(costs)) return false

    // 创建建筑
    const buildingId = `${templateId}_${Date.now()}`
    const building: Building = {
      id: buildingId,
      name: template.name,
      description: template.description,
      category: template.category,
      level: 1,
      maxLevel: template.maxLevel,
      costs,
      buildTime: calculateBuildTime(template, 1),
      maintenance: template.baseStats.consumption,
      effects: [],
      unlockConditions: template.unlockConditions,
      planetId,
      isActive: true,
      icon: template.icon
    }

    buildings.value[buildingId] = building

    // 添加到建造队列
    const queueItem: BuildingQueueItem = {
      id: `queue_${Date.now()}`,
      buildingId,
      planetId,
      startTime: Date.now(),
      endTime: Date.now() + building.buildTime * 1000,
      progress: 0
    }
    buildQueue.value.push(queueItem)

    // 添加生产效果
    updateBuildingProduction(building)

    return true
  }

  function upgradeBuilding(buildingId: string): boolean {
    const building = buildings.value[buildingId]
    if (!building || building.level >= building.maxLevel) return false

    const template = buildingTemplates.value[building.id.split('_')[0]]
    if (!template) return false

    const newLevel = building.level + 1
    const costs = calculateBuildCosts(template, newLevel)

    if (!resourcesStore.canAfford(costs)) return false
    if (!resourcesStore.payCosts(costs)) return false

    // 升级建筑
    building.level = newLevel
    building.costs = costs
    building.buildTime = calculateBuildTime(template, newLevel)

    // 更新生产效果
    updateBuildingProduction(building)

    return true
  }

  function demolishBuilding(buildingId: string): boolean {
    const building = buildings.value[buildingId]
    if (!building) return false

    // 移除生产效果
    removeBuildingProduction(building)

    // 返还部分资源
    const refund = building.costs.map(cost => ({
      ...cost,
      amount: Math.floor(cost.amount * 0.5) // 返还50%
    }))
    
    refund.forEach(cost => {
      resourcesStore.addResource(cost.resourceId, cost.amount)
    })

    // 删除建筑
    delete buildings.value[buildingId]

    return true
  }

  function toggleBuilding(buildingId: string): boolean {
    const building = buildings.value[buildingId]
    if (!building) return false

    building.isActive = !building.isActive
    
    if (building.isActive) {
      updateBuildingProduction(building)
    } else {
      removeBuildingProduction(building)
    }

    return true
  }

  function updateBuildQueue(deltaTime: number) {
    buildQueue.value.forEach((item, index) => {
      const totalTime = item.endTime - item.startTime
      const elapsed = Date.now() - item.startTime
      item.progress = Math.min(elapsed / totalTime, 1)

      if (item.progress >= 1) {
        // 建造完成
        const building = buildings.value[item.buildingId]
        if (building) {
          building.isActive = true
          updateBuildingProduction(building)
        }
        
        // 从队列中移除
        buildQueue.value.splice(index, 1)
      }
    })
  }

  function updateBuildingProduction(building: Building) {
    const template = buildingTemplates.value[building.id.split('_')[0]]
    if (!template) return

    // 移除旧的生产效果
    removeBuildingProduction(building)

    // 添加新的生产效果
    template.baseStats.production.forEach(prod => {
      const scaledProduction = {
        ...prod,
        amount: prod.amount * building.level * getEfficiencyMultiplier(building)
      }
      resourcesStore.addProduction(building.id, scaledProduction)
    })
  }

  function removeBuildingProduction(building: Building) {
    const template = buildingTemplates.value[building.id.split('_')[0]]
    if (!template) return

    template.baseStats.production.forEach(prod => {
      resourcesStore.removeProduction(building.id, prod.resourceId)
    })
  }

  function getEfficiencyMultiplier(building: Building): number {
    let multiplier = 1.0

    // 应用行星加成
    planetaryBonuses.value.forEach(bonus => {
      if (bonus.buildingId === building.id || bonus.buildingId === '*') {
        if (bonus.modifier === 'multiply') {
          multiplier *= (1 + bonus.value)
        } else {
          multiplier += bonus.value
        }
      }
    })

    return multiplier
  }

  function calculateBuildCosts(template: BuildingTemplate, level: number) {
    // 基础成本随等级指数增长
    const multiplier = Math.pow(1.5, level - 1)
    
    return [
      { resourceId: 'metal', amount: Math.floor(100 * multiplier) },
      { resourceId: 'crystal', amount: Math.floor(50 * multiplier) },
      { resourceId: 'energy', amount: Math.floor(25 * multiplier) }
    ]
  }

  function calculateBuildTime(template: BuildingTemplate, level: number): number {
    // 建造时间随等级增长
    return 60 + (level - 1) * 30 // 秒
  }

  function checkUnlockConditions(conditions: any[]): boolean {
    // 简化的解锁条件检查
    return true
  }

  function getBuildingsByPlanet(planetId: string): Building[] {
    return Object.values(buildings.value).filter(b => b.planetId === planetId)
  }

  function getBuildingsByCategory(category: string): Building[] {
    return buildingsByCategory.value[category] || []
  }

  function getBuildingTemplate(templateId: string): BuildingTemplate | undefined {
    return buildingTemplates.value[templateId]
  }

  function addPlanetaryBonus(bonus: PlanetaryBonus) {
    planetaryBonuses.value.push(bonus)
  }

  return {
    // 状态
    buildings,
    buildingTemplates,
    buildQueue,
    planetaryBonuses,
    
    // 计算属性
    buildingsByCategory,
    buildingsByPlanet,
    totalBuildingEffects,
    buildingCount,
    activeBuildingCount,
    
    // 动作
    initializeBuildingTemplates,
    buildBuilding,
    upgradeBuilding,
    demolishBuilding,
    toggleBuilding,
    updateBuildQueue,
    getBuildingsByPlanet,
    getBuildingsByCategory,
    getBuildingTemplate,
    addPlanetaryBonus
  }
})